/*
 * DA2.c
 *  Author: Henry
 */ 
#include <avr/io.h>
#include <avr/interrupt.h>
void delay(void);co

int volatile count=0;

int main(void)
{
	DDRB = 0xFF;		//Set PORTB to output
	DDRC = 0x30;		//Set PORTC.4 and C.5 to output
	PIND = 0x04;		//Set Port.D2(INT0) to input
	PORTB = 0x00;		//Initialize PORTB to 0
	PORTC = 0x00;		//Initialize PORTC to 0
	
	TCNT0 = 0x00;		//Initialize Timer0

	EIMSK |= (1 << INT0);	//Enable INT0 Interrupt
	EICRA |= (1 << ISC01);	//Falling Edge of INT0 generates interrupt request
	sei();
	
	//Timer 0:
	//Normal Mode, 256 prescalar, clock from T0 on rising edge
	TCCR0A = 0;
	TCCR0B = (1 << CS02) | (1 << CS01) | (1 <<CS00);
	
    while(1)
    {
		PORTB = TCNT0;			//Output 8-bit Counter to PORTC
		delay();				//elapse 0.25s
    }
}
ISR(INT0_vect){
	count++;
	if((count%5)==0)
		PORTC ^= (1<<4);
}
void delay(){
	TCNT1 = 0x85EE;			//Set Timer1 count value to 34286 for delay of 0.25s
	TCCR1A = 0x00;			//Set Timer1 mode to Normal mode
	TCCR1B = (1 << CS11) | (1 << CS10);	//64 Prescalar
	while((TIFR1 & (1<<TOV1)) == 0){} //Run for 0.25s
	TCCR1B = 0x00;
	TCCR1A = 0x00;			//Stop Timer1
	PORTC ^= (1 << 5);		//Toggle PORTB.5
	TIFR1 = 1<<TOV1;		//Reset flag register
}